<template>
  <el-scrollbar max-height="400px">
    <div v-for="item in addRequest" :key="item" class="scrollbar-demo-item">
      <el-avatar style="margin-left: 5px" shape="square" :src="url+item.avatar"/>
      <div style="width: 180px">{{item.name}}添加你为好友</div>
      <div>
        <el-icon @click="agreeFri(item)" style="color:#1aff00"><Select /></el-icon>
        <el-icon style="color: red" @click="refusalFri(item)"><CloseBold /></el-icon>
      </div>
    </div>
  </el-scrollbar>

  <el-input style="margin-top: 20px" v-model="filterText" placeholder="好友查询" />

  <el-tree style="margin:10px 0"
           draggable
           ref="treeRef"
           :data="data"
           class="filter-tree"
           :filter-node-method="filterNode"
           :allow-drop="allowDrop"
           :allow-drag="allowDrag"
           @node-drop="handleDrop"
  >
    <template #default="{ node, data }">
        <span class="custom-tree-node">
          <span>{{ data.label }}</span>
          <span style="margin-left: auto;display: inline-block;">
            <a style="margin: 2px" v-if="data.children == null " @click="toInfo(data)"> <el-icon><Avatar /></el-icon> </a>
            <a style="margin: 2px"  v-if="data.children == null" @click="append(data)"> <el-icon><ChatLineSquare /></el-icon> </a>
            <a style="margin: 2px" v-if="data.label !== '默认分组'" @click="remove(node, data)"> <el-icon><DeleteFilled /></el-icon> </a>
          </span>
        </span>
    </template>
  </el-tree>

  <el-row class="mb-4">
    <el-button type="primary" @click="friendGroupShow=true">添加分组</el-button>
    <el-button style="margin-left: auto" type="success" @click="addFriendShow=true">添加好友</el-button>
  </el-row>

  <el-dialog v-model="friendGroupShow" title="添加分组">
    <el-form>
      <el-form-item label="分组名" :label-width="formLabelWidth">
        <el-input v-model="friendGroup.name" autocomplete="off" style="width: 600px"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="quitFriendGroup">返回</el-button>
        <el-button type="primary" @click="addFriendGroup">
          提交
        </el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog v-model="addFriendShow" title="添加好友">
    <el-form>
      <el-form-item label="好友账号" :label-width="formLabelWidth">
        <el-input v-model="friend.userNumber" autocomplete="off" style="width: 600px"/>
      </el-form-item>
      <el-form-item label="添加到的分组" :label-width="formLabelWidth">
        <el-select v-model="friend.friendGroupId" placeholder="分组" @click="get">
          <el-option v-for="item in group" :key="item.friendGroupId" :label="item.name" :value="item.friendGroupId" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="quitFriend">退出</el-button>
        <el-button type="primary" @click="addFriend1">
          添加
        </el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog v-model="agreeFriendShow" title="选择分组">
    <el-form>
      <el-form-item label="添加到的分组" :label-width="formLabelWidth">
        <el-select v-model="add.friendGroupId" placeholder="分组" @click="get">
          <el-option v-for="item in group" :key="item.friendGroupId" :label="item.name" :value="item.friendGroupId" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="exit">退出</el-button>
        <el-button type="primary" @click="agreeS">
          同意添加
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {useRouter} from "vue-router";
import {
  addFriend,
  agree,
  createFriendGroup,
  getFriendAddMessage,
  getFriendGroup,
  getFriendShowVo, moveFriendGroup, refusal, removeFriend, removeFriendGroup
} from "../../service/TieApi";
import {onMounted, reactive, Ref, ref, watch} from "vue";
import {confirm, error, notifyMessage, success, websocketNotify} from "../../utils/messageUtil";
import {createSession} from "../../service/ChatApi";
import {callbacks, MessageDto, SessionType} from "../../utils/webSocket";
import {ElTree} from "element-plus";
import {userInfo} from "../../utils/constant";
import {DragEvents} from "element-plus/es/components/tree/src/model/useDragNode";
import {AllowDropType, NodeDropType} from "element-plus/es/components/tree/src/tree.type";
const router = useRouter();

const url = ref(import.meta.env.VITE_APP_BASE_API + "/common/file/loadFileId?fileId=")
const addRequest:Ref<any[]> = ref([]);
const visible = ref(false)

const handleDrop = (draggingNode: any, dropNode: any) => {
  console.log('tree drag end:', draggingNode, dropNode)
  moveFriendGroup({
    friendId:draggingNode.data.value,
    friendGroupId:dropNode.data.value
  }).then(d=>{
    //如果不成功恢复数据
    if(d.data.code!=200){
      getDate()
    }
  }).catch(()=>{
    error("网络异常")
  })
}

const allowDrop = (draggingNode: any, dropNode: any, type: AllowDropType) => {
  return dropNode.data.children != null;
}
const allowDrag = (draggingNode: any) => {
  return draggingNode.data.children == null;
}

const emit = defineEmits(['clickChild'])

const clickChild=(session:any)=> {
  //传递给父组件
  emit('clickChild', session)
}

const append = (data: Tree) => {
  console.log(data)
  createSession({
    acceptId: data.value,
    sessionType: SessionType.ALONG
  }).then(d=>{
    if(d.data.code == "200") {
      clickChild(d.data.date);
      router.push({
        name: 'chat',
        query: d.data.date
      })
    }else{
      error(d.data.message)
    }
  }).catch(()=>{
    error("网络错误")
  })
}

const toInfo = (data:Tree) => {
  router.push({
    name:'info',
    query:{
        userId:data.value,
    }
  })
}

const remove = (node: Node, data: Tree) => {
  console.log(node, data)
  //是好友分组
  if(data.children != null){
      confirm("删除分组", "确定删除该分组，若存在好友移动至默认分组", () => {
        removeFriendGroup({
          friendGroupId:data.value
        }).then(d=>{
          if(d.data.code==200){
            success("删除成功")
            getDate();
          }else{
            error(d.data.message)
          }
        }).catch(()=>{
          error("网络异常")
        })
      });
  }else{
      confirm("删除好友", "如果删除好友所有信息都会清空", () => {
        removeFriend({
          friendId:data.value
        }).then(d=>{
          if(d.data.code==200){
            //通知获取新数据
            clickChild({
              sessionId:data.value,
              type:'remove'
            })
            getDate();
            success("删除成功")
          }else{
            error(d.data.message)
          }
        }).catch(()=>{
          error("网络异常")
        })
      });
  }
}

const add = ref({
  id:'',
  friendGroupId:''
})

const agreeFri = (data:any)=>{
  add.value.id = data.id
  agreeFriendShow.value = true;
}

const refusalFri = (data:any)=>{
  refusal({
      id:data.id
  }).then(d=>{
    if(d.data.code==200){
      getAddRequest()
    }else{
      error(d.data.message)
    }
  }).catch(()=>{
    error("网络异常")
  })
}

const exit = () => {
  agreeFriendShow.value=false;
  add.value.id=''
  add.value.friendGroupId=''
}

const agreeS = () => {
  if(add.value.friendGroupId==''){
    error("请选择添加的分组")
    return;
  }
  agree(add.value).then(d=>{
    if(d.data.code==200){
      getAddRequest()
      getDate()
      exit()
    }else{
      error(d.data.message)
    }
  }).catch(()=>{
    error("网络异常")
  })
}

const getAddRequest = ()=>{
  getFriendAddMessage().then(d=>{
    if(d.data.code==200){
      addRequest.value = d.data.date
    }else{
      error(d.data.message)
    }
  }).catch(()=>{
    error("网络异常")
  })
}


const friendGroupShow = ref(false)
const addFriendShow = ref(false)
const agreeFriendShow = ref(false)
const formLabelWidth = '140px'

const group:Ref<any[]> = ref([])

const get = ()=>{
  getFriendGroup().then(d=>{
    if(d.data.code==200){
      group.value = d.data.date
    }else{
      error(d.data.message)
    }
  }).catch(()=>{
    error("网络异常")
  })
}

const friend = reactive(  {
  userNumber:'',
  friendGroupId:''
})


const quitFriend = ()=>{
  addFriendShow.value = false
  friend.userNumber = '';
  friend.friendGroupId = '';
}

const addFriend1 = ()=>{
  addFriend(friend).then(d=>{
    if(d.data.code==200){
      success("发送成功")
      addFriendShow.value = false;
      friend.userNumber = '';
      friend.friendGroupId = '';
    }else{
      error(d.data.message)
    }
  }).catch(()=>{
    error("网络异常")
  })
}

const friendGroup = reactive({
  name:''
})

const quitFriendGroup = ()=>{
  friendGroupShow.value = false;
  friendGroup.name = '';
}

const addFriendGroup = ()=>{
  createFriendGroup(friendGroup).then(d=>{
    if(d.data.code==200){
      data.value.push({
        value:'',
        label: friendGroup.name,
        children:[]
      })
      friendGroupShow.value = false;
      friendGroup.name = '';
    }else{
      error(d.data.message)
    }
  }).catch(()=>{
    error("网络异常")
  })
}

const filterText = ref('')
const treeRef = ref<InstanceType<typeof ElTree>>()

watch(filterText, (val:any) => {
  treeRef.value!.filter(val)
})

const filterNode = (value: string, data: any) => {
  if (!value) return true
  return data.label.includes(value)
}

interface Tree {
  label: string
  value?:string
  children?: Tree[]
}

onMounted(()=>{
  getDate();
  getAddRequest();
  callbacks.addFriendRequest= (messageDto:MessageDto)=>{
    notifyMessage(`${messageDto.sendUserSocketDto.name}`+'添加您为好友')
    getAddRequest()
    getDate()
  }
})

const getDate = ()=>{
  getFriendShowVo().then(d=>{
    if(d.data.code == 200) {
      data.value = d.data.date as Tree[];
    }else{
      error(d.data.message)
    }
  }).catch(()=>{
    error("网络错误")
  })
}

const data = ref<Tree[]>([]);
</script>

<style scoped>

.scrollbar-demo-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  margin: 10px;
  text-align: center;
  border-radius: 4px;
  background: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  width: 220px;
}
</style>